﻿namespace Anley.DomainDrivenDesign.Contract.Extension;

/// <summary>
/// 字符串扩展类
/// </summary>
public static class StringExtension
{
    /// <summary>
    /// 字符串转Base64字符串
    /// </summary>
    /// <param name="value"></param>
    public static string StringToBase64String(
        this string value)
    {
        if (string.IsNullOrWhiteSpace(value))
            return string.Empty;
        var bytes = Encoding.UTF8.GetBytes(value);
        return Convert.ToBase64String(bytes);
    }

    /// <summary>
    /// Base64字符串转字符串
    /// </summary>
    /// <param name="base64String"></param>
    public static string Base64StringToString(
        this string base64String)
    {
        if (string.IsNullOrWhiteSpace(base64String))
            return string.Empty;
        var bytes = Convert.FromBase64String(base64String);
        return Encoding.UTF8.GetString(bytes);
    }

    /// <summary>
    /// 16进制字符串转字节
    /// </summary>
    /// <param name="hexString"></param>
    public static byte[] HexStringToBytes(
        this string hexString)
    {
        if (string.IsNullOrWhiteSpace(hexString))
            throw new ArgumentNullException(nameof(hexString));
        if (hexString.Length % 2 != 0)
            throw new ArgumentException(nameof(hexString));
        var bytes = new byte[hexString.Length / 2];
        for (int i = 0; i < bytes.Length; i++)
            bytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
        return bytes;
    }
}